package com.ben.xinyue.seckill.service;

import com.ben.basic.exception.BaseResponse;
import com.ben.basic.exception.DefaultSuccessEnum;
import com.ben.xinyue.seckill.converter.MiaoshaUserConverter;
import com.ben.xinyue.seckill.domain.dto.MiaoshaUserDto;
import com.ben.xinyue.seckill.domain.entity.MiaoshaUser;
import com.ben.xinyue.seckill.domain.vo.LoginVo;
import com.ben.xinyue.seckill.mapper.MiaoshaUserMapper;
import com.ben.xinyue.seckill.util.MD5Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.factory.Mappers;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MiaoshaUserService  {

    private final MiaoshaUserMapper miaoshaUserMapper;
    private final RedissonClient redissonClient;

    /**
     * 根据ID 查询用户
     * @param id ID
     * @return 结果
     */
    private MiaoshaUserDto findById(Long id){
        MiaoshaUserDto userDto = (MiaoshaUserDto) redissonClient.getBucket("userId"+id).get();
        if(Objects.nonNull(userDto)){
            return userDto;
        }
        MiaoshaUser miaoshaUser = miaoshaUserMapper.selectById(id);
        MiaoshaUserConverter converter = Mappers.getMapper(MiaoshaUserConverter.class);
        MiaoshaUserDto miaoshaUserDto = converter.entity2Dto(miaoshaUser);
        redissonClient.getBucket("userId"+id).set(miaoshaUserDto);
        return miaoshaUserDto;
    }

    /**
     * 登录
     * @param loginVo 登录人
     */
    public BaseResponse login(HttpServletResponse response,LoginVo loginVo) {

        MiaoshaUserDto miaoshaUserDto = findById(Long.valueOf(loginVo.getMobile()));
        String dbPass = miaoshaUserDto.getPassword();
        String calcPass = MD5Util.formPassToDBPass(loginVo.getPassword(), miaoshaUserDto.getSalt());
        if(!StringUtils.equals(dbPass, calcPass)){
            return BaseResponse.error("密码错误!");
        }
        // 此处为方便直接用UserId 作为token
        redissonClient.getBucket("userId_"+miaoshaUserDto.getId()).set(miaoshaUserDto);
        addCookie(response, "userId_"+miaoshaUserDto.getId(), miaoshaUserDto);
        return BaseResponse.business(DefaultSuccessEnum.LOGIN_SUCCESS);
    }

    /**
     * 根据TOKEN 获取用户
     * @param response 回应
     * @param token token
     * @return 结果
     */
    public MiaoshaUser getByToken(HttpServletResponse response, String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        MiaoshaUser user = (MiaoshaUser)redissonClient.getBucket(token).get();
        if(user != null) {
            addCookie(response, token, user);
        }
        return user;
    }

    /**
     * 添加Cookie
     * @param response response
     * @param token token
     * @param user 用户
     */
    private void addCookie(HttpServletResponse response, String token, MiaoshaUser user) {
        redissonClient.getBucket("userId_"+user.getId()).set(user);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(3600*24 * 2);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}